package com.powernode.shop.oauth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.powernode.shop.oauth.constant.AuthConstant;
import com.powernode.shop.oauth.domain.SysUser;
import com.powernode.shop.oauth.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author ZHAOZHENYU
 * @since 2022/10/9
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 加载数据库用户名验证 账密
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 得到request对象
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = servletRequestAttributes.getRequest();
        // 得到请求头的类型是 管理员还是 普通用户
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (StringUtils.isEmpty(loginType))return null;
        switch (loginType){
            case AuthConstant.SYS_USER:
                SysUser sysUser = sysUserMapper.selectOne(new QueryWrapper<SysUser>().eq("username", username));
                if (!ObjectUtils.isEmpty(sysUser)) {
                    List<String> authList = sysUserMapper.selectAuthById(sysUser.getUserId());
                    // 得到菜单集合放到 实现了userDetails的实体类转化为权限对象
                    if (!CollectionUtils.isEmpty(authList))sysUser.setAuths(authList);
                }
                return sysUser;
            case AuthConstant.USER:
                //前端用户登陆，这里使用微信小程序认证
        }
        return null;
    }
}
